<!-- 探针配置管理 -->
<template>
	<div class="container">
		<!--查询列表-->
		<YdTable
			ref="multipleTable"
			:formData="formData"
			:tableConfig="tableConfig"
			:tableData="tableData"
			@sizeChangeHandler="queryGrid"
			@currentChangeHandler="queryGrid"
			@sortChangeHandler="queryGrid"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog v-model="open.moduleAddDialog" :title="title" width="600px" append-to-body center :close-on-click-modal="false" @close="cancelModule">
			<el-form ref="probeForm" :model="form" :rules="rules" label-width="150px">
				<el-row>
					<el-col :span="24">
						<el-form-item label="模块名称:" prop="moduleName"> 探针模块 </el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="模块IP:" prop="moduleIp">
							<el-input v-model="form.moduleIp" placeholder="请输入模块IP" style="width: 200px" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="copyForm">确 定</el-button>
				<el-button @click="cancelModule">取 消</el-button>
			</template>
		</el-dialog>

		<!--配置详情-->
		<el-dialog
			v-model="open.configDetailDialog"
			:title="title"
			width="900px"
			append-to-body
			center
			:close-on-click-modal="false"
			@close="cancelConfig"
		>
			<div class="halfDiv leftDiv">
				<div>
					<!--按钮-->
					<el-row :gutter="10" style="padding-left: 17px; padding-bottom: 15px">
						<el-col :span="1.5">
							<div :class="buttonIsDisabled(addDialogForm.singleSelect)" :disabled="addDialogForm.singleSelect" @click="updateProbeHandle">
								<svg-icon icon-class="yd-icon-edit" class="icon-style" circle></svg-icon>
								<span class="icon-title" style="margin-left: 2px; margin-right: 15px; font-size: 14px"> 修改 </span>
							</div>
						</el-col>
						<el-col :span="1.5">
							<div @click="saveProbeHandle">
								<svg-icon icon-class="yd-icon-plus" class="icon-style" circle></svg-icon>
								<span class="icon-title" style="margin-left: 2px; margin-right: 15px; font-size: 14px"> 保存 </span>
							</div>
						</el-col>
						<el-col :span="1.5">
							<div @click="cancelProbeHandle">
								<svg-icon icon-class="yd-icon-delete" class="icon-style" circle></svg-icon>
								<span class="icon-title" style="margin-left: 2px; margin-right: 15px; font-size: 14px"> 取消 </span>
							</div>
						</el-col>
						<el-col :span="1.5">
							<div @click="refreshProbeHandle">
								<svg-icon icon-class="yd-icon-sync" class="icon-style" circle></svg-icon>
								<span class="icon-title" style="margin-left: 2px; margin-right: 15px; font-size: 14px"> 更新配置 </span>
							</div>
						</el-col>
					</el-row>

					<div style="height: 500px">
						<!--查询列表-->
						<el-table
							ref="probeTable"
							v-loading="addDialogForm.loading"
							:data="addDialogForm.probeList"
							height="100%"
							@selection-change="probeSelectionChangeHandle"
						>
							<el-table-column type="selection" width="50" align="center" />
							<el-table-column label="参数名" align="center" prop="configName">
								<template #default="scope">
									<span>{{ scope.row.configName }}</span>
								</template>
							</el-table-column>
							<el-table-column label="参数值" align="center" prop="configDetails">
								<template #default="scope">
									<span v-if="scope.row.enable">
										<el-input v-model="scope.row.configDetails"></el-input>
									</span>
									<span v-else>{{ scope.row.configDetails }}</span>
								</template>
							</el-table-column>
							<el-table-column label="备注" align="center" prop="remark">
								<template #default="scope">
									<span v-if="scope.row.enable">
										<el-input v-model="scope.row.remark"></el-input>
									</span>
									<span v-else>{{ scope.row.remark }}</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</div>
			</div>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="cancelConfig">关 闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="ProbeConfig" lang="ts">
import {
	queryProbeModuleList,
	addProbeModule,
	editProbeModule,
	copyProbeModule,
	deleteProbeModuleByIds,
	queryProbeModuleById,
	queryProbeConfigDetails,
	updateProbeConfigDetails,
} from '@/api/management/probeManage/probeConfig';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { ref, reactive, toRefs, onMounted } from 'vue';

const { proxy } = useCurrentInstance();

// 总条数
const total = ref(0);
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<any>([]);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref('');
// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
//点击配置详情的时候选中的模块信息
let selectModule = reactive({});
// 是否显示弹出层
let open = reactive({
	moduleAddDialog: false,
	configDetailDialog: false,
});
let addDialogForm = reactive<anyObj>({
	ids: [],
	singleSelect: true,
	loading: true,
	probeList: [],
	tempProbeList: [],
});
// 表单校验
const rules = ref({
	moduleIp: [
		{ required: true, message: '模块IP不能为空', trigger: 'blur' },
		{
			validator: function (rule: any, value: string, callback: any) {
				if (
					!/^((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){3}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9]))$/.test(
						value
					)
				) {
					callback(new Error('请输入合法IP地址'));
				} else {
					callback();
				}
			},
			trigger: 'blur',
		},
	],
});
// 搜索表单数据
let formData = reactive<anyObj>({});
// 列表配置
let tableConfig = reactive({
	url: queryProbeModuleList,
	columns: [
		{
			label: '模块名称',
			prop: 'realModuleName',
		},
		{
			label: 'GROUPID',
			prop: 'moduleId',
		},
		{
			label: '模块IP',
			prop: 'moduleIp',
		},
		{
			label: '模块端口',
			prop: 'modulePort',
		},
		{
			label: '运行状态',
			prop: 'runningStatus',
			formatter(row: anyObj, val: ApiVal) {
				if (val === 0) {
					return '否';
				} else {
					return '是';
				}
			},
		},
		{
			label: '心跳时间',
			prop: 'runningHeartTime',
		},
		{
			label: '更新配置标记',
			prop: 'updateConfigFlag',
			formatter(row: anyObj, val: ApiVal) {
				// -1: 更新失败  0: 初始化  1:更新成功  2: 待更新  3: 更新中
				if (val === -1) {
					return '更新失败';
				} else if (val === 0) {
					return '初始化';
				} else if (val === 1) {
					return '更新成功';
				} else if (val === 2) {
					return '待更新';
				} else {
					return '更新中';
				}
			},
		},
		{
			label: '更新配置时间',
			prop: 'moduleUpdateTime',
		},
		{
			label: '最后修改时间',
			prop: 'updateTime',
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['probeModuleConfig:add'], handler: () => addHandle() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['probeModuleConfig:edit'], disable: 'single', handler: () => updateHandle() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['probeModuleConfig:delete'], disable: 'multiple', handler: () => deleteHandle() },
		{ name: '一键复制', icon: 'yd-icon-plus', permi: ['probeModuleConfig:copy'], disable: 'single', handler: () => copyHandle() },
		{
			name: '配置详情',
			icon: 'yd-icon-list',
			permi: ['probeModuleConfig:detail'],
			disable: 'single',
			handler: () => configDetailHandle(),
		},
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = ref([]);
const probeForm = ref<any>();
const probeTable = ref<any>();
const multipleTable = ref<any>();

onMounted(() => {
	searchHandler();
});

// 搜索
function searchHandler() {
	tableConfig.pagination.pageNum = 1;
	queryGrid();
}
//查询列表数据
function queryGrid() {
	tableConfig.loading = true;
	queryProbeModuleList(formData).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			tableConfig.loading = false;
			return;
		}
		tableConfig.loading = false;
		tableData.value = res.data.records;
		tableConfig.pagination.total = res.data.total;
	});
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: anyObj) => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
/** 新增按钮操作 */
function addHandle() {
	reset();
	title.value = '增加配置信息';
	open.moduleAddDialog = true;
}
/** 修改按钮操作 */
function updateHandle() {
	reset();
	title.value = '修改配置信息';
	open.moduleAddDialog = true;
	const id = ids.value;
	if (id === null || id === '') {
		proxy.$modal.msgWarning('请选择要修改的配置信息。');
		return;
	}
	queryProbeModuleById(id).then((response) => {
		form.value = response.data[0];
	});
}
/** 复制按钮操作 */
function copyHandle() {
	const id = ids.value;
	if (id === null || id === '') {
		proxy.$modal.msgWarning('请选择要复制的配置信息。');
		return;
	}
	reset();
	title.value = '复制配置信息';
	open.moduleAddDialog = true;
}
/** 删除按钮操作 */
function deleteHandle() {
	if (ids.value === null) {
		proxy.$modal.msgWarning('请选择要删除的配置信息。');
		return;
	}
	proxy.$modal
		.confirm('是否需要删除已经勾选的配置数据?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deleteProbeModuleByIds(ids.value).then((res) => {
				if (res.code === 0) {
					proxy.$modal.msgSuccess('删除成功');
					searchHandler();
				} else {
					proxy.$modal.msgWarning(res.msg);
				}
			});
		})
		.catch(() => {});
}
/** 提交按钮 */
function submitForm() {
	probeForm.value.validate((valid: any) => {
		if (valid) {
			//新增或者修改提交前先校验表达式
			if (form.value.id !== undefined) {
				editProbeModule(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('修改成功');
						open.moduleAddDialog = false;
						searchHandler();
					} else {
						proxy.$modal.msgWarning(response.msg);
						return;
					}
				});
			} else {
				form.value.moduleName = 'BPM_PROBE';
				form.value.moduleId = '-1';
				form.value.modulePort = '';
				addProbeModule(form.value).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('新增成功');
						open.moduleAddDialog = false;
						searchHandler();
					} else {
						proxy.$modal.msgWarning(response.msg);
						return;
					}
				});
			}
		}
	});
}
function copyForm() {
	probeForm.value.validate((valid: any) => {
		if (valid) {
			form.value.moduleName = 'BPM_PROBE';
			form.value.moduleId = '-1';
			form.value.modulePort = '';
			addProbeModule(form.value).then((response) => {
				if (response.code === 0) {
					proxy.$modal.msgSuccess('新增成功');
					open.moduleAddDialog = false;
					searchHandler();
				} else {
					proxy.$modal.msgWarning(response.msg);
					return;
				}
			});
		}
	});
}
// 取消按钮
function cancelModule() {
	open.moduleAddDialog = false;
	reset();
}
// 表单重置
function reset() {
	form.value = {
		moduleIp: undefined,
	};
	probeForm.value?.resetFields();
}
//--------打开配置详情 弹出框
async function configDetailHandle() {
	const id = ids.value;
	await queryProbeModuleById(id).then((response) => {
		selectModule = response.data[0];
	});
	title.value = '配置详情信息';
	open.configDetailDialog = true;
	queryProbeConfigGrid();
}
//探针列表数据
function queryProbeConfigGrid() {
	addDialogForm.loading = true;
	const module: anyObj = selectModule;
	queryProbeConfigDetails(module.moduleIp).then((res) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			addDialogForm.loading = false;
			return;
		}
		addDialogForm.loading = false;
		addDialogForm.probeList = res.data;
		//深复制
		addDialogForm.tempProbeList = JSON.parse(JSON.stringify(res.data));
	});
}
// 多选框选中数据
function probeSelectionChangeHandle(selection: any) {
	addDialogForm.ids = selection.map((item: anyObj) => item.id);
	addDialogForm.singleSelect = selection.length !== 1;
}
// 取消按钮
function cancelConfig() {
	open.configDetailDialog = false;
	multipleTable.value.getTableRef().clearSelection();
}
//修改探针配置信息
function updateProbeHandle() {
	const ids = addDialogForm.ids;
	if (ids === null || ids.length < 1) {
		proxy.$modal.msgWarning('请选择需要修改的配置信息');
		return;
	}
	const data = addDialogForm.probeList;
	let num = 0;
	let tempItem;
	if (data !== null && data.length > 0) {
		for (let i = 0; i < data.length; i++) {
			const item = data[i];
			if (item.enable) {
				num = num + 1;
			}
			if (item.id === ids[0]) {
				tempItem = item;
			}
		}
	}
	if (num === 0) {
		console.log(tempItem);
		tempItem.enable = true;
	} else {
		proxy.$modal.msgWarning('已经有正在编辑的数据，请先保存');
		return;
	}
}
//保存探针配置信息
function saveProbeHandle() {
	const data = addDialogForm.probeList;
	if (!data || data.length <= 0) {
		return;
	}
	let item = null;
	for (let i = 0; i < data.length; i++) {
		if (data[i].enable) {
			item = data[i];
		}
	}
	if (!item) {
		proxy.$modal.msgWarning('没有要保存的信息');
		return;
	}
	verifyProbe(item);
}
// 探针配置值保存校验
function verifyProbe(item: anyObj) {
	if (item.configName === null || item.configName === '') {
		proxy.$modal.msgWarning('参数名不能为空');
		return;
	}
	if (item.configDetails === null || item.configDetails === '') {
		proxy.$modal.msgWarning('参数值不能为空');
		return;
	}
	const regex = /^[0-9,]*$/;
	const configdetail = item.configDetails.split(',');
	switch (item.configType) {
		case 'string':
			if (item.configDetails.indexOf(' ') >= 0) {
				proxy.$modal.msgWarning('参数名:' + item.configName + '的值不能包含空格');
				return;
			}
			if (item.configDetails.length > 300) {
				proxy.$modal.msgWarning('参数名:' + item.configName + '的值过长');
				return;
			}
			break;
		case 'int':
			if (
				!regex.test(item.configDetails) ||
				item.configDetails.indexOf(',') === 0 ||
				item.configDetails.indexOf(',', item.configDetails.length - 1) === item.configDetails.length - 1
			) {
				proxy.$modal.msgWarning('参数名:' + item.configName + '的值格式不正确');
				return;
			}
			for (let k = 0; k < configdetail.length; k++) {
				if (configdetail[k] > parseInt(item.maxValue) || configdetail[k] < parseInt(item.minValue)) {
					proxy.$modal.msgWarning('参数名:' + item.configName + '的值的范围不准确');
					return;
				}
				if (configdetail[k].trim() === '' || configdetail[k] === null) {
					proxy.$modal.msgWarning('参数名:' + item.configName + '的值格式不正确');
					return;
				}
			}
			break;
		case 'bool':
			if (item.configDetails !== '0' && item.configDetails !== '1') {
				proxy.$modal.msgWarning('参数名:' + item.configName + '的值只能为0或者1');
				return;
			}
			break;
	}
	//设置为不可编辑状态
	item.enable = false;
	probeTable.value.clearSelection();
}
//取消
function cancelProbeHandle() {
	addDialogForm.probeList = [];
	addDialogForm.probeList = JSON.parse(JSON.stringify(addDialogForm.tempProbeList));
}
function refreshProbeHandle() {
	//当前选择的模块配置信息
	const module: anyObj = selectModule;
	//探针配置信息
	const data = addDialogForm.probeList;
	if (module !== null && data !== null && data.length > 0) {
		for (let i = 0; i < data.length; i++) {
			if (data[i].enable) {
				proxy.$modal.msgSuccess('有正在修改的数据，请先保存再更新！');
				return;
			}
		}
		let newString = '';
		let arr = [];
		let showFlag = 0;
		let configName;
		let configDetails;
		let remark;
		// console.log(data);
		for (let i = 0; i < data.length; i++) {
			const item = data[i];
			configName = item.configName;
			configDetails = item.configDetails;
			remark = item.remark;
			// if ((configName !== '' && configName !== undefined && configDetails !== '' && configDetails !== undefined) || (item.minValue === 0 && item.configType === 'string')) {
			let str = '{"configName":"' + configName + '","configDetails":"' + configDetails + '","remark":"' + remark + '"}';
			arr.push(str);
			newString = arr.join(',');
			// } else {
			// 	showFlag = 1;
			// }
		}
		// if (showFlag === 1) {
		// 	//恢复原来的值
		// 	cancelProbeHandle();
		// 	proxy.$modal.msgWarning('不允许添加空值');
		// 	return;
		// }
		newString = '[' + newString + ']';
		proxy.$modal
			.confirm('确定更新配置吗？', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				cancelButtonClass: 'confirm-rigth-cancel-button',
				type: 'warning',
			})
			.then(() => {
				updateProbeConfigDetails({
					id: module.id,
					configContext: newString,
				}).then((response) => {
					if (response.code === 0) {
						proxy.$modal.msgSuccess('更新成功');
						searchHandler();
					} else {
						proxy.$modal.msgSuccess('更新失败');
						return;
					}
				});
			})
			.catch(() => {});
	}
}
//按钮css 控制
function buttonIsDisabled(val: any) {
	if (val) {
		return 'disabled';
	}
	return 'enabled';
}
</script>

<style lang="scss" scoped></style>
